import React, { useEffect, useState } from 'react';
import { Collapse } from 'antd';
import { CaretRightOutlined } from '@ant-design/icons';

import LineItem from './LineItem';
import { getFeishuMagicTimeline } from '../../api/feishu';

const { Panel } = Collapse;

interface resItemsForm {
  fields: {
    key: string;
    time: Date;
    years?: string;
  };
  id: string;
}

interface LineItemForm {
  id: string;
  content: string;
  date: Date;
}

function TimelinePage(props: any) {
  const [lineItems, setLineItems] = useState({});

  // 获取飞书魔法师时间线数据
  useEffect(() => {
    getFeishuMagicTimeline().then(res => {
      formatData(res);
    }).catch(err => {
      console.log(err);
    });
  }, []);

  // 飞书数据处理
  const formatData = ({ data }: {
    data: {
      items: resItemsForm[]
    }
  }) => {
    const { items } = data;
    const obj = {};
    items.forEach((item) => {
      if (!obj[item.fields.years]) {
        obj[item.fields.years] = [];
      } else {
        obj[item.fields.years].push({
          id: item.id,
          content: item.fields.key,
          date: item.fields.time,
        });
      }
    });
    setLineItems(obj);
  };

  const renderPanels = () => {
    if (lineItems) {
      return Object.keys(lineItems).map((year) => (
      <Panel header={year} key={year}>
        {
          lineItems[year].map((item: LineItemForm) => (
            <LineItem
              key={item.id}
              time={item.date}
              text={item.content}
            />
          ))
        }
      </Panel>
      ));
    } else {
      return null;
    }
  };

  return (
    <div className='timeline'>
      <Collapse
        bordered={false}
        defaultActiveKey={[2016]}
        expandIcon={({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />}
      >
        {renderPanels()}
      </Collapse>
    </div>
  );
};

export default TimelinePage;
